package com.androidnetframe.utils;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcelable;
import android.text.TextUtils;

import com.androidnetframe.ConfigUtil;
import com.lidroid.xutils.http.RequestParams;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/7/19 0019.
 */
public class UIUtils {
    public static void simpleStartActivity(Context context, Class cls) {
        Intent intent = new Intent(context, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public static void simpleStartActivity(Class cls) {
        simpleStartActivity(ConfigUtil.context, cls);
    }

    public static void startActivityWithParams(Parcelable params, Class cls) {
        Intent intent = new Intent(ConfigUtil.context, cls);
        intent.putExtra(params.getClass().getName(), params);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ConfigUtil.context.startActivity(intent);
    }

    public static HashMap<String, Object> objToHash(Object obj, RequestParams params) throws IllegalArgumentException, IllegalAccessException {

        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        Class clazz = obj.getClass();
        List<Class> clazzs = new ArrayList<Class>();

        do {
            clazzs.add(clazz);
            clazz = clazz.getSuperclass();
        } while (!clazz.equals(Object.class));

        for (Class iClazz : clazzs) {
            Field[] fields = iClazz.getDeclaredFields();
            for (Field field : fields) {
                Object objVal = null;
                field.setAccessible(true);
                objVal = field.get(obj);

                String tmpValue = "";
                if (objVal instanceof Integer) {
                    int tmpInt = (Integer) objVal;
                    tmpValue = tmpInt + "";
                } else if (objVal instanceof String) {
                    tmpValue = (String) objVal;
                } else if (objVal instanceof Float) {
                    float tmpFloat = (Float) objVal;
                    tmpValue = tmpFloat + "";
                }

                //有些字段是编译器自动生成的，如$change,
                String name = field.getName();
                if(!TextUtils.isEmpty(name) && !(name.startsWith("$"))){
                    params.addBodyParameter(field.getName(), tmpValue);
                    hashMap.put(field.getName(), objVal);
                }
            }
        }

        return hashMap;
    }

    public static String getClientTokenId(){
        SharedPreferences sp = ConfigUtil.context.getSharedPreferences("TokenId_Folder", 0);
        String tokenId = sp.getString("TokenId", "");

        return tokenId;
    }
}
